<?php

namespace app\mini\controller\salesman;

use app\common\controller\ApiController;
use app\common\enum\order\GoodsType;
use app\common\exception\BaseException;
use app\common\model\CompanyWarehouse;
use app\common\model\DealerGoods;
use app\common\model\DealerGoodsSpec;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyWarehouseGoods;
use app\mini\model\Cart as CartModel;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation (title="购物车相关")
 */
class Cart extends ApiController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CartModel();
    }

    /**
     * @NodeAnnotation (title="购物车列表")
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function list(): Json
    {
        $get = $this->request->get();
        if (empty($get['store_id'])) {
            return $this->error('门店参数缺失！');
        }
        $rule = [
                'store_id|门店'     => 'require',
                'warehouse_id|仓库' => 'require',
                'type|购物车类型'   => 'require'
        ];
        $this->validate($get, $rule);
        $where = [
                ['store_id', '=', $get['store_id']],
                ['salesman_id', '=', $this->uid],
                ['company_warehouse_id', '=', $get['warehouse_id']],
        ];
        if ($get['type'] == 1) {
            $where[] = ['goods_type', 'in', [1, 2]];
        } else {
            $where[] = ['goods_type', '=', 3];
        }
        $data = $this->model->with([
                                           'goods' => function ($query)
                                           {
                                               $query->withField('id,name,code69,image');
                                           },
                                           'spec'  => function ($query)
                                           {
                                               $query->withField('id,name,unit,image,stock');
                                           },
                                   ])->where($where)->select();
        $list = [
                'pt'          => ['cate_num' => 0, 'goods_num' => 0, 'goods' => []],
                'send'        => ['cate_num' => 0, 'goods_num' => 0, 'goods' => []],
                'return'      => ['cate_num' => 0, 'goods_num' => 0, 'goods' => []],
                'total_money' => 0,
        ];
        foreach ($data as $item) {
            if ($item['goods_type'] == GoodsType::SALE) {
                $list['pt']['goods'][]   = $item;
                $list['pt']['cate_num']  += 1;
                $list['pt']['goods_num'] += $item['num'];
            } else if ($item['goods_type'] == GoodsType::GIFT) {
                $list['send']['goods'][]   = $item;
                $list['send']['cate_num']  += 1;
                $list['send']['goods_num'] += $item['num'];
            } else if ($item['goods_type'] == GoodsType::RETURN_GOODS) {
                $list['return']['goods'][]   = $item;
                $list['return']['cate_num']  += 1;
                $list['return']['goods_num'] += $item['num'];
            }
            $list['total_money'] = bcadd($list['total_money'], $item['total_price'], 2);
        }
        return $this->success($list);
    }

    /**
     * @NodeAnnotation (title="新增购物车")
     * @param Request $request
     * @return Json
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'store_id|门店'     => 'require',
                'warehouse_id|仓库' => 'require',
                'detail|商品'       => 'require',
        ];
        $this->validate($post, $rule);
        try {
            $post['detail'] = json_decode($post['detail'], true);
            foreach ($post['detail'] as $k => &$item) {
                // 验证库存，根据规格比换算出小规格数量，匹配商品表中的售卖库存，或者company_warehouse_goods表中的库存
                /*$ratio = DealerGoodsSpec::where('id', $item['dealer_goods_spec_id'])->value('ratio');
                $num   = bcmul($item['num'], $ratio, 2);
                // 判断仓库类型
                $warehouseType = CompanyWarehouse::where('id', $post['warehouse_id'])->value('type');
                if ($warehouseType == 1) {
                    $stock = DealerGoods::where('id', $item['dealer_goods_id'])->value('sale_stock');
                } else {
                    $stock = CompanyWarehouseGoods::where([
                                                                  'warehouse_id' => $post['warehouse_id'],
                                                                  'dealer_goods_id'      => $item['dealer_goods_id']
                                                          ])
                                                  ->value('stock');
                }
                if ($stock < $num) throw new BaseException(['message' => '库存不足']);*/
                $cartInfo = $this->model->where([
                                                        'store_id'             => $post['store_id'],
                                                        'salesman_id'          => $this->uid,
                                                        'goods_type'           => $item['goods_type'],
                                                        'dealer_goods_id'      => $item['dealer_goods_id'],
                                                        'dealer_goods_spec_id' => $item['dealer_goods_spec_id'],
                                                        'company_warehouse_id' => $post['warehouse_id']
                                                ])->find();
                if (!$cartInfo) {
                    $item['company_id']           = $this->companyId;
                    $item['salesman_id']          = $this->uid;
                    $item['store_id']             = $post['store_id'];
                    $item['company_warehouse_id'] = $post['warehouse_id'];
                    $item['sale_price']           = DealerGoodsSpec::where('id', $item['dealer_goods_spec_id'])
                                                                   ->value('sale_price');
                    $item['total_price']          = $item['true_price'] * $item['num'];
                } else {
                    $cartInfo->save([
                                            'num'                  => $cartInfo['num'] + $item['num'],
                                            'true_price'           => $item['true_price'],
                                            'total_price'          => $cartInfo['total_price'] + $item['true_price'] * $item['num'],
                                            'company_warehouse_id' => $post['warehouse_id']
                                    ]);
                    unset($post['detail'][$k]);
                }
            }
            $this->model->saveAll($post['detail']);
            return $this->success('添加成功');
        } catch (\Exception $e) {
            return $this->error('添加失败:' . $e->getMessage() . $e->getLine());
        }
    }

    /**
     * @NodeAnnotation (title="编辑购物车")
     * @param Request $request
     * @return Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        //        if (empty($post['store_id'])) {
        //            return $this->error('门店参数缺失！');
        //        }
        try {
            if(isset($post['num']) && $post['num'] < 0) throw new BaseException(['message' => '数量不能小于0']);
//            if(isset($post['true_price']) && $post['true_price'] < 0) throw new BaseException(['message' => '金额不能小于0']);
            if($row->goods_type == 2) $post['true_price'] = 0;
            if($row->goods_type == 3) $post['true_price'] = -abs($post['true_price']);
            $row->save([
                'num' => $post['num'],
                'true_price' => $post['true_price'],
                'total_price' => bcmul($post['num'],$post['true_price'],2),
            ]);
            return $this->success('修改成功');
        } catch (\Exception $e) {
            return $this->error('修改失败:' . $e->getMessage() . $e->getLine());
        }
    }

    /**
     * @NodeAnnotation (title="删除购物车")
     * @param Request $request
     * @return Json
     */
    public function del(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        //        if (empty($post['store_id'])) {
        //            return $this->error('门店参数缺失！');
        //        }
        $cartIds = explode(",", $post['id']);
        try {
            $this->model->destroy($cartIds, true);
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->error('删除失败:' . $e->getMessage() . $e->getLine());
        }
    }
}